package com.kaduoxee.ebooks.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaduoxee.ebooks.entity.Chapter;
import com.kaduoxee.ebooks.entity.ChapterContent;
import com.kaduoxee.ebooks.mapper.ChapterMapper;
import com.kaduoxee.ebooks.mapper.ContentMapper;
import com.kaduoxee.ebooks.service.ChapterService;
import com.kaduoxee.ebooks.util.JsoupUtil;
import lombok.SneakyThrows;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter>
        implements ChapterService {

    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private ChapterMapper chapterMapper;

    /**
     * @param doc       网页对应document对象
     * @param fictionId 章节与章节内容对应小说的id
     * @author kaduoxee
     * @since 2023/6/6
     */
    @SneakyThrows
    @SuppressWarnings({"ConstantConditions", "unsed"})
    public void saveChaptersAndContents(Document doc, Integer fictionId) {
        Element listDiv = doc.selectFirst("#list");
        Elements aList = listDiv.select("a");
        int sort = 1;
        for (Element a : aList) {
            try {

                ChapterContent chapterContent = JsoupUtil.writeContent(a.attr("href"));
                contentMapper.insert(chapterContent);

                Chapter chapter = JsoupUtil.writeChapter(a, fictionId, sort++, chapterContent.getId());
                chapterMapper.insert(chapter);
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
            System.out.println("爬取了第" + (sort - 1) + "章");
        }
    }

    /**
     *
     * @param fictionId 小说id
     * @return 小说最新章节对应sort
     */
    public Integer newestOfFic(Integer fictionId) {
        return chapterMapper.fictionMS(fictionId);
    }



}
